import json
import time

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from Applications.Security.ControlRequests.OpenGate import OpenGate
from Applications.Security.models import Record
from Django_Admin.settings import IMAGE_URL

# Create your views here.



# TODO 返回开门记录相关信息API

class RecordsAPI(View):
    def get(self, request):
        records = Record.objects.all()[::-1]
        result = {}

        # TODO Records数据
        json_list = []
        chart = {}
        for record in records:
            json_dict = {}
            json_dict["ID"] = record.id
            json_dict["User"] = record.username
            open_time = str(record.open_time)[:19]
            json_dict["Time"] = open_time
            avatar_url = IMAGE_URL + str(record.avatar)
            json_dict["Snapshoot"] = avatar_url
            json_dict["Limit"] = record.limit
            json_list.append(json_dict)

        # TODO Charts数据
        chart_dict = {}
        chart_labels = []
        chart_data = []
        index = 0
        start = 0
        base = 0
        for chart in records:
            day = str(chart.open_time)[5:10]
            if len(chart_dict) < 10:
                chart_dict[day] = chart_dict.get(day, 0) + 1
            else:
                break

        for chart in chart_dict:
            chart_labels.append(chart)
            data = chart_dict.get(chart)
            chart_data.append(data)
        result['records'] = json_list
        result['chart_labels'] = chart_labels[::-1]
        result['chart_data'] = chart_data[::-1]
        return JsonResponse(result, safe=False)
    def post(self, request):
        pass





# TODO 对门锁终端发起开锁请求
@method_decorator(csrf_exempt, name='dispatch')

class OpenGateAPI(View):
    def get(self, request):
        pass
    def post(self, request):
        username = request.POST.get("username")
        password = request.POST.get("password")
        isLogin = False
        isAdmin = "用户"
        open_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if username == "" or password == "":
            return HttpResponse(403)
        if username == "Louis" and password == "201314abc":
            isAdmin = "管理员"
            isLogin = True
        elif username == "dzz" and password == "702702702":
            isLogin = True
        if isLogin == True:
            record = Record(username=username, open_time=open_time, limit=isAdmin)
            record.save()
            openGate = OpenGate()
            openGate.sendRequest(username)
            return HttpResponse(200)
        else:
            print(username)
            print(password)
            return HttpResponse(404)